﻿#region Librerias

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ESF.General;

#endregion


namespace ESF.Web.ServerControls
{
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:QueryOrderbyShowParams runat=server></{0}:QueryOrderbyShowParams>")]
	public class QueryOrderbyShowParams : WebControl, INamingContainer, IPostBackEventHandler
	{
		#region Constantes

		public const string SESSION_BOOKMARKS = "Bookmarks";

		#endregion


		#region Delegados

		public delegate void ShowHideParams (bool pShowHide);

		public event ShowHideParams ShowingHidingParams;


		public delegate void BrowsingBookmarks (List<string> pBookmarks);

		public event BrowsingBookmarks BrowseBookmarks;


		public delegate void ClearingBookmars ();

		public event ClearingBookmars ClearBookmarks;


		public delegate void ChangingPageSize (int pPageSize);

		public event ChangingPageSize ChangePageSize;

		#endregion


		#region Propiedades

		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		public string FieldListKeyValue
		{
			set
			{
				EnsureChildControls ();
				
				
				ListLoader.LoadListItems (ddlOrderByField, value, '|');
				ListLoader.RemoveSelectItem (ddlOrderByField);
			}
		}


		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		public string OnBrowseJS
		{
			set
			{
				ViewState ["OnBrowseJS"] = value;
			}
			get
			{
				return ViewState ["OnBrowseJS"] as string;
			}
		}


		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		public string OrderByField
		{
			get
			{
				EnsureChildControls ();

				return ddlOrderByField.SelectedValue;
			}
		}


		public string OrderDirection
		{
			get
			{
				EnsureChildControls();

				return ddlOrderDirection.SelectedValue;
			}
		}


		public int PageSize
		{
			set 
			{ 
				EnsureChildControls ();
				
				ListLoader.Select (ddlPageSize, value);
			}
			get 
			{
				EnsureChildControls ();
				
				return TextHelper.GetInt (this.ddlPageSize.SelectedValue, 10);
			}
		}


		public string BookmarksTitle
		{
			set
			{
				EnsureChildControls ();

				this.lblBookmarks_Title.Text = value;
			}
			get
			{
				EnsureChildControls ();

				return this.lblBookmarks_Title.Text;
			}
		}


		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("true")]
		public bool EnableShowParams
		{
			set
			{
				EnsureChildControls ();

				chkShowHideParams.Enabled = value;
			}
		}


		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("true")]
		public bool EnablePageSize
		{
			set
			{
				EnsureChildControls ();

				ddlPageSize.Enabled = value;
			}
		}


		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("true")]
		public bool EnableOrderby
		{
			set
			{
				EnsureChildControls ();

				ddlOrderByField.Enabled = value;
			}
		}


		public bool ShowHideParamsCheck
		{
			set
			{
				EnsureChildControls ();
				
				chkShowHideParams.Checked = value;

				if (ShowingHidingParams != null)
				{
					ShowingHidingParams (value);
				}
			}
			get
			{
				return chkShowHideParams.Checked;
			}
		}


		public static List<string> Bookmarks
		{
			get
			{
				List<string> bookmars;


				bookmars = HttpContext.Current.Session [SESSION_BOOKMARKS] as List<string>;

				if (bookmars == null) { bookmars = new List<string> (); }

				return bookmars;
			}
			set
			{
				HttpContext.Current.Session [SESSION_BOOKMARKS] = value;
			}
		}

		#endregion


		#region Miembros

		private DropDownList ddlOrderByField;
		private DropDownList ddlOrderDirection;
		private DropDownList ddlPageSize;

		private CheckBox chkShowHideParams;

		private LinkButton lnkBookmarks_Clear;
		private HyperLink lnkBookmarks_Browse;

		private Label lblBookmarks_Title;
		private Label lblBookmarks_Count;

		#endregion


		#region Inicializar

		protected override void CreateChildControls()
		{
			ddlOrderByField = new DropDownList ();
			ddlOrderByField.CssClass = "ddlOrderByField";
			ddlOrderByField.ID = "ddlOrderByField";
			ddlOrderByField.ToolTip = "Al cambiar la selección se utilizara este campo como criterio de ordenamiento cuando ejecute la consulta";

			ddlPageSize = new DropDownList ();
			ddlPageSize.ToolTip = "Al cambiar la selección se presentaran mas o menos elementos cuando ejecute la consulta";
			ddlPageSize.CssClass = "ddlPageSize";
			ddlPageSize.ID = "ddlPageSize";
			ddlPageSize.AutoPostBack = true;
			ddlPageSize.SelectedIndexChanged += ddlPageSize_SelectedIndexChanged;

			ddlOrderDirection = new DropDownList ();
			ddlOrderDirection.CssClass = "ddlOrderDirection";
			ddlOrderDirection.ID = "ddlOrderDirection";
			ddlOrderDirection.ToolTip = "Determina la direccion del ordenamiento del campo seleccionado";

			chkShowHideParams = new CheckBox ();
			chkShowHideParams.CssClass = "chkShowHideParams";
			chkShowHideParams.Checked = true;
			chkShowHideParams.AutoPostBack = true;
			chkShowHideParams.ID = "chkShowHideParams";
			chkShowHideParams.ToolTip = "Al estar marcado este campo los parametros de consultas estaran visibles, de lo contrario estaran ocultos";
			chkShowHideParams.CheckedChanged += chkShowHideParams_CheckedChanged;

			lblBookmarks_Title = new Label ();
			lblBookmarks_Title.ID = "lblBookmarks_Title";
			lblBookmarks_Title.CssClass = "lblBookmarks_Title";
			lblBookmarks_Title.Text = "Bibliografía";

			lnkBookmarks_Browse = new HyperLink ();
			lnkBookmarks_Browse.ID = "lnkBookmarks_Browse";
			lnkBookmarks_Browse.CssClass = "lnkBookmarks_Browse";
			lnkBookmarks_Browse.Text = "Ver";
			lnkBookmarks_Browse.ToolTip = "De click para ver en la consulta exclusivamente el listado de elementos que ha marcado";
			lnkBookmarks_Browse.NavigateUrl = "#";

			lnkBookmarks_Clear = new LinkButton ();
			lnkBookmarks_Clear.ID = "lnkBookmarks_Clear";
			lnkBookmarks_Clear.CssClass = "lnkBookmarks_Clear";
			lnkBookmarks_Clear.Text = "Limpiar";
			lnkBookmarks_Clear.ToolTip = "Limpia el listado de elementos que ha marcado en los resultados de sus consultas";
			lnkBookmarks_Clear.Click += lnkBookmarks_Clear_Click;

			lblBookmarks_Count = new Label ();
			lblBookmarks_Count.ID = "lblBookmarks_Count";
			lblBookmarks_Count.CssClass = "lblBookmarks_Count";
			lblBookmarks_Count.ToolTip = "Observe aqui el numero de elementos que ha marcado en sus consultas";

			ListLoader.LoadListPageSize (ddlPageSize);
			
			ListLoader.LoadListItems(ddlOrderDirection, "Ascendente", "ASC", "Descendente", "DESC");
			ListLoader.RemoveSelectItem(ddlOrderDirection);


			Controls.Add (ddlOrderDirection);
			Controls.Add (ddlOrderByField);
			Controls.Add (ddlPageSize);
			Controls.Add (chkShowHideParams);
			Controls.Add (lnkBookmarks_Browse);
			Controls.Add (lnkBookmarks_Clear);
			Controls.Add (lblBookmarks_Count);
			Controls.Add (lblBookmarks_Title);
		}

		#endregion


		#region Funciones

		public void Clear ()
		{
			ddlPageSize.SelectedValue = "10";
			ddlOrderByField.SelectedIndex = -1;
			ddlOrderDirection.SelectedIndex = -1;
			chkShowHideParams.Checked = true;
		}

		#endregion


		#region Manejo de Bookmarks

		public static void AddRemoveBookmark (bool pMark, string pBookmark)
		{
			List<string> bookmarks;


			bookmarks = Bookmarks;

			
			if (pMark)
			{
				if (bookmarks.Count == 500)
				{
					throw new GenericInfoException ("La lista de elementos marcados esta en su limite (500) no se agregarán mas elementos");
				}

				if (!bookmarks.Contains (pBookmark))
				{
					bookmarks.Add (pBookmark);
				}
			}
			else
			{
				bookmarks.Remove (pBookmark);
			}

			Bookmarks = bookmarks;
		}


		private void ClearTheBookmarks ()
		{
			Bookmarks = null;

			if (ClearBookmarks != null)
			{
				ClearBookmarks ();
			}
		}


		public static bool IsThereBookmark (string pBookmark)
		{
			if (string.IsNullOrWhiteSpace (pBookmark)) { return false; }

			return Bookmarks.Contains (pBookmark);
		}

		#endregion


		#region Eventos

		protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (ChangePageSize != null)
			{
				ChangePageSize (PageSize);
			}
		}
		
		
		protected void lnkBookmarks_Clear_Click(object sender, EventArgs e)
		{
			ClearTheBookmarks ();
		}


		protected void chkShowHideParams_CheckedChanged(object sender, EventArgs e)
		{
			if (ShowingHidingParams != null)
			{
				ShowingHidingParams (chkShowHideParams.Checked);
			}
		}

		#endregion


		#region Render

		protected override void OnPreRender(EventArgs e)
		{
			lblBookmarks_Count.Text = Bookmarks.Count.ToString ();

			if (BrowseBookmarks != null)
			{
				lnkBookmarks_Browse.Attributes ["onclick"] = Page.ClientScript.GetPostBackClientHyperlink (lnkBookmarks_Browse, "Browse");
			}

			if (!string.IsNullOrEmpty (OnBrowseJS))
			{
				lnkBookmarks_Browse.Attributes ["onclick"] = OnBrowseJS;
			}
		}


		protected override void RenderContents(HtmlTextWriter pWriter)
		{
				pWriter.AddAttribute (HtmlTextWriterAttribute.Class, (string.IsNullOrEmpty (CssClass) ? "divQueryOrderbyShowParams" : CssClass));			
			pWriter.RenderBeginTag (HtmlTextWriterTag.Div);

				if (chkShowHideParams.Checked)
				{				
					if (ddlOrderByField.Enabled)
					{
							pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "field orderBy");
						pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
					
								pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "label");
							pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
								pWriter.Write ("Ordenar por:");
							pWriter.RenderEndTag();

							ddlOrderByField.RenderControl (pWriter);
							ddlOrderDirection.RenderControl (pWriter);

						pWriter.RenderEndTag();
					}

					if (ddlPageSize.Enabled)
					{
							pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "field");
						pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
								pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "label");
							pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
								pWriter.Write ("Resultados:");
							pWriter.RenderEndTag();

							ddlPageSize.RenderControl (pWriter);
						pWriter.RenderEndTag();
					}
				}


				if (chkShowHideParams.Enabled)
				{
						pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "field");
					pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
							pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "label");
						pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
							pWriter.Write ("Filtros");
						pWriter.RenderEndTag();

						chkShowHideParams.RenderControl (pWriter);
					pWriter.RenderEndTag();
				}
				
					pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "field");
				pWriter.RenderBeginTag (HtmlTextWriterTag.Div);						
					
						pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "label");
					pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
						lblBookmarks_Title.RenderControl (pWriter);
						lblBookmarks_Count.RenderControl (pWriter);
					pWriter.RenderEndTag();

				pWriter.RenderEndTag();

					pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "field");
				pWriter.RenderBeginTag(HtmlTextWriterTag.Div);

					lnkBookmarks_Browse.RenderControl (pWriter);
					lnkBookmarks_Clear.RenderControl(pWriter);
					
				pWriter.RenderEndTag();
				
			pWriter.RenderEndTag();
		}

		#endregion


		#region Eventos de postback

		public void RaisePostBackEvent(string pEventArgument)
		{
			if (pEventArgument == "Browse")
			{
				if (BrowseBookmarks != null)
				{
					BrowseBookmarks (Bookmarks);
				}
			}
		}

		#endregion
	}
}
